<!--测试任务列表-->
<template>
  <div class="firmware-list">
    <div class="header">
      <div class="title"></div>
      <el-button
        :disabled="rolesCode === 'SALE'"
        type="add"
        size="14"
        icon="el-icon-plus"
        @click="dialogVisible = true">新建测试任务</el-button>
    </div>
    <el-table :data="tableData" style="width: 100%" :header-cell-style="{ background: '#F5F6F7' }" size="medium">
      <el-table-column prop="name" label="任务名称"> </el-table-column>
      <el-table-column prop="createTime" label="创建时间"> </el-table-column>
      <el-table-column :formatter="statusFormatter" label="状态"></el-table-column>
      <el-table-column fixed="right" label="操作" width="270">
        <template slot-scope="scope">
          <el-button type="text" size="operate" @click="handleDetails(scope.row)">详情</el-button>
          <el-button
            v-if="scope.row.state == 0"
            type="text"
            size="operate"
            :disabled="rolesCode === 'SALE'"
            @click="terminateTestTaskFun(scope.row)">终止</el-button>
          <el-button
            v-if="scope.row.state == 2"
            :disabled="rolesCode === 'SALE'"
            type="text"
            size="operate"
            @click="deleteTestTaskFun(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="current"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>

    <el-dialog
      v-loading="uploadLoading"
      title="新建测试任务"
      :visible.sync="dialogVisible"
      width="628px"
      :before-close="handleClose"
      :close-on-click-modal="false"
      custom-class="test-task-dialog">
      <el-form ref="form" :rules="rules" :model="form" label-width="140px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="任务名称" prop="name">
              <template #label>
                <span>任务名称</span>&nbsp;
                <el-tooltip content="支持中英文和数字,长度2-32,名称不可重复" placement="bottom" effect="light">
                  <i class="iconfont icon-wenhao"></i>
                </el-tooltip>
              </template>
              <el-input v-model="form.name" placeholder="请输入任务名称">
              </el-input>
            </el-form-item>
            <el-form-item label="任务类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择任务类型" clearable>
                <el-option v-for="item in typeList" :key="item.type" :label="item.name" :value="item.type">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="升级版本号" prop="currentVersion">
              <el-input
                v-model="form.currentVersion"
                minlength="1"
                :disabled="true"
                show-word-limit
                placeholder="当前版本号"></el-input>
            </el-form-item>
            <el-form-item label="可升级版本号" prop="downgradeVersion">
              <el-select
                v-model="form.downgradeVersion"
                clearable
                placeholder="请选择可升级版本号"
                @change="downgradeVersionChange">
                <el-option
                  v-for="item in DowngradeVersionList"
                  :key="item.id"
                  :label="item.version"
                  :value="item.version">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="单次超时时长" prop="singleTimeout">
              <template #label>
                <span>单次超时时长</span>&nbsp;
                <el-tooltip content="1-120分钟" placement="top">
                  <i class="iconfont icon-wenhao"></i>
                </el-tooltip>
              </template>
              <el-input v-model="form.singleTimeout" type="number" max="120" min="1" placeholder="请输入">
                <template slot="append">秒</template>
              </el-input>
            </el-form-item>
            <el-form-item label="升降级次数" prop="executionNumber">
              <el-input v-model="form.executionNumber" maxlength="200" show-word-limit placeholder="请输入升降级次数"></el-input>
            </el-form-item>
            <el-form-item label="特定设备" prop="deviceId">
              <el-input
                v-model="form.deviceId"
                maxlength="200"
                show-word-limit
                placeholder="请输入设备id , 只支持一个设备"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="14" @click="handleClose()">取 消</el-button>
        <el-button type="primary" size="14" @click="submitForm('form')">保存</el-button>
      </span>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-drawer title="测试任务详情" :visible.sync="drawer" :direction="direction" size="720px">
      <div v-loading="taskLoading">
        <div class="taskInfo">
          <div class="InfoTitle">任务基本信息
            <el-button
              type="add"
              size="mini"
              icon="el-icon-refresh-right"
              class="refresh"
              @click="handleDetails">刷新</el-button> </div>
          <div class="martop-16"><span class="left">任务名称</span><span class="right">{{ taskInfo.name }}</span></div>
          <div class="martop-16"><span class="left">任务类型</span><span class="right">{{ taskInfo.type }}</span></div>
          <div class="martop-16"><span class="left">升级版本号</span><span class="right">{{ form.currentVersion }}</span></div>
          <div class="martop-16"><span class="left">可升级版本号</span><span class="right">{{ taskInfo.downgradeVersion
          }}</span>
          </div>
        </div>
        <div class="taskInfo">
          <div class="InfoTitle">任务执行结果</div>
          <div class="martop-16"><span class="left">升降级次数</span><span class="right">{{ taskInfo.executionNumber }}</span>
          </div>
          <div class="martop-16"><span class="left">执行次数</span><span class="right">{{ taskInfo.finishNumber }}</span>
          </div>
          <div class="martop-16"><span class="left">执行成功次数</span><span class="right">{{ taskInfo.finishSuccessNumber
          }}</span></div>
          <a :href="dynamicLink" rel="opener" target="_blank">
            <el-button
              type="add"
              size="mini"
              class="refresh">查看ota任务具体数据</el-button>
          </a>
        </div>
      </div>

    </el-drawer>
  </div>
</template>
<script>
import { getTestTaskList, addTestTask, getDowngradeVersionList, getTestTaskTypeList, deleteTestTask, terminateTestTask, getTestTaskInfo } from "@/api/product/product-details"
import { mapGetters } from 'vuex'
export default {
  name: "testDetails",
  data() {
    // const validateDeviceUuid = (rule, value, callback) => {
    //   if (value === '') {
    //     callback(new Error('请输入特定设备id'))
    //   } else {
    //     const deviceList = this.form.deviceId.split(/[;；\s]/)
    //     if (deviceList.length > 1) {
    //       callback(new Error('仅支持一个设备ID'))
    //     } else {
    //       callback()
    //     }
    //   }
    // }
    return {
      tableData: [], // 表格数据
      dialogVisible: false,
      form: {
        name: "", //测试任务名称
        type: "", //任务类型
        downgradeVersion: "", //降级版本号
        singleTimeout: "", //单次超时时长
        executionNumber: "", //升降级次数
        deviceId: "", //特定设备id
        currentFirmwareId: "", //当前固件id
        currentVersion: "", //当前固件版本
        downgradeFirmwareId: "" // 降级固件id
      },
      rules: {
        name: [
          { required: true, message: '请输入任务名称', trigger: 'blur' },
          { min: 2, max: 32, message: '请输入规范的任务名称', trigger: 'blur' },
          { validator: this.validateName, trigger: 'blur' }
        ],
        type: [{ required: true, message: "请选择任务类型", trigger: "change" }],
        downgradeVersion: [{ required: true, message: "请选择可升级版本号", trigger: "change" }],
        singleTimeout: [
          { required: true, message: '请输入单次超时时长', trigger: 'blur' }
          // { validator: this.validateSingleTimeout, trigger: 'blur' }
        ],
        executionNumber: [
          { required: true, message: "请输入升降级次数", trigger: "blur" },
          {},
          { validator: this.validateExecutionNumber, trigger: 'blur' }
        ],
        deviceId: [
          { required: true, message: '请输入特定设备id', trigger: 'blur' },
          { min: 1, max: 200, message: '请输入规范的特定设备id', trigger: 'blur' },
          { validator: this.validateDeviceId, trigger: 'blur' }
        ]

      },
      uploadLoading: '', //新建测试任务弹窗的loading
      firmwareId: '', //当前固件id
      id: '', //当前固件id
      current: 1, //当前页面
      size: 10, //一页展示多少条
      total: 0, //总条数
      stateList: [
        //状态
        { value: 0, label: "执行中" },
        { value: 1, label: "执行完成" },
        { value: 2, label: "终止" }
      ],
      typeOptions: [], //任务类型
      DowngradeVersionList: [], //降级任务版本号
      typeList: [], //测试任务任务类型
      version: '', //当前版本号
      productId: "", //当前产品id
      drawer: false, //测试任务详情弹窗
      direction: 'rtl', //测试任务详情弹窗方向
      taskInfo: '', //测试任务详情弹窗展示信息
      taskId: '', //当前详情的测试任务id
      taskLoading: false //测试任务详情弹窗loading
    }
  },
  computed: {
    ...mapGetters(['rolesCode']),
    dynamicLink() {
      return `#/product/product-details/taskExecutionRecord?taskId=${this.taskId}`
    }
  },
  created() { },
  mounted() {
    this.productId = this.$route.query.productId
    this.firmwareId = this.$route.query.firmwareId
    this.id = this.$route.query.id
    this.version = this.$route.query.version
    this.form.currentFirmwareId = this.$route.query.firmwareId //当前固件id
    this.form.currentVersion = this.$route.query.version //当前固件版本
    this.getTestTaskListFun()
    this.getDowngradeVersionListFun()
    this.getTestTaskTypeListFun()
  },
  methods: {
    // 任务名称校验
    validateName(rule, value, callback) {
      const flag = new RegExp(/^[\u4E00-\u9FA5A-Za-z0-9]+$/).test(value)
      if (!flag) {
        callback(new Error('请输入规范的任务名称'))
      } else {
        callback()
      }
    },
    // 单次超时时长校验提示
    // validateSingleTimeout(rule, value, callback) {
    //   const regex = /^(?:1[0-1]\d|120|[1-9]\d?)$/
    //   if (!regex.test(value)) {
    //     callback(new Error('请输入正确的单次超时时长'))
    //   } else {
    //     callback()
    //   }
    // },
    // 特定设备id校验
    validateDeviceId(rule, value, callback) {
      const flag = new RegExp(/^\d+$/).test(value)
      if (!flag) {
        callback(new Error('请输入规范的特定设备id'))
      } else {
        callback()
      }
    },
    // 升降级次数校验
    validateExecutionNumber(rule, value, callback) {
      const flag = new RegExp(/^[1-9]\d{0,2}$|1000$/).test(value)
      if (!flag) {
        callback(new Error('请输入规范的升降级次数'))
      } else {
        callback()
      }
    },
    // 测试任务列表数据
    handleDetails(row) {
      this.drawer = true
      this.taskLoading = true
      if (row.id) {
        this.taskId = row.id
      }
      const params = {
        taskId: row.id || this.taskId
      }
      getTestTaskInfo(params).then((res) => {
        this.taskInfo = res.data.data
        this.taskInfo.type = this.typeFormatter(res.data.data)
        this.taskLoading = false
      }).catch((err) => {
        this.$message.error(err.message)
        this.taskLoading = false
      })
    },
    // 新建测试任务弹窗关闭
    handleClose() {
      this.dialogVisible = false
      this.$refs['form'].resetFields()
    },
    // 每页条数改变时触发
    handleSizeChange(val) {
      this.size = val
      this.getTestTaskListFun()
    },
    // 当前页变时触发
    handleCurrentChange(val) {
      this.current = val
      this.submitForm('form')
      this.getTestTaskListFun()
    },
    //状态格式化
    statusFormatter(val) {
      const label = this.stateList.find((option) => option.value === val.state).label || "-"
      return label
    },
    // 任务类型格式化
    typeFormatter(val) {
      const label = this.typeList.find((option) => option.type === val.type).name || "-"
      return label
    },
    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addTestTaskFun()
        } else {
          return false
        }
      })
    },
    // 新建测试任务
    addTestTaskFun() {
      this.uploadLoading = true
      addTestTask(this.form).then((res) => {
        this.$message.success('新建成功')
        this.handleClose()
        this.getTestTaskListFun()
        this.dialogVisible = false
        this.$refs['form'].resetFields()
        this.uploadLoading = false
      }).catch((err) => {
        this.$message.error(err.message)
        this.uploadLoading = false
      })
    },
    // 获取测试任务降级版本号
    getDowngradeVersionListFun() {
      var params = {
        firmwareId: this.firmwareId,
        productComponentRelationId: this.id
      }
      getDowngradeVersionList(params).then((res) => {
        if (res.data.code === 0) {
          this.DowngradeVersionList = res.data.data
        }
      })
    },
    // 获取测试任务类型
    getTestTaskTypeListFun() {
      getTestTaskTypeList().then((res) => {
        if (res.data.code === 0) {
          this.typeList = res.data.data
        }
      })
    },
    // 获取测试任务列表
    getTestTaskListFun() {
      const params = {
        size: this.size,
        current: this.current,
        firmwareId: this.firmwareId,
        productComponentRelationId: this.id
      }
      getTestTaskList(params).then((res) => {
        this.tableData = res.data.data.records
        this.total = res.data.data.total
      }).catch((err) => {
        this.$message.error(err.message)
      })
    },
    // 获取降级固件id
    downgradeVersionChange(item) {
      const foundItem = this.DowngradeVersionList.find(obj => obj.version === item)
      if (foundItem) {
        this.form.downgradeFirmwareId = foundItem.id
      }
    },
    // 删除测试任务
    deleteTestTaskFun(row) {
      const params = {
        taskId: row.id
      }
      this.$confirm('确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteTestTask(params).then((res) => {
          this.getTestTaskListFun()
        }).catch((err) => {
          this.$message.error(err.message)
        })
      })
    },
    // 终止测试任务
    terminateTestTaskFun(row) {
      const params = {
        taskId: row.id
      }
      terminateTestTask(params).then((res) => {
        this.getTestTaskListFun()
      }).catch((err) => {
        this.$message.error(err.message)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

::v-deep .el-textarea .el-input__count {
  background: transparent;
  right: 20px;
}

::v-deep .el-dialog__body {
  padding: 40px 58px 36px 50px;
}

::v-deep .el-form-item__label {
  color: #808080;
}

::v-deep .el-input-group__append {
  background-color: #ffffff;
  color: #808080;
}

::v-deep .el-button+.el-button {
  margin-left: 16px;
}

::v-deep .name-input .el-input__inner {
  padding-left: 15px;
  padding-right: 48px;
  background: transparent;
}

::v-deep .el-table__fixed-right-patch {
  background-color: #F5F6F7;
}

.title {
  font-weight: 600;
  font-size: 14px;
}

.header {
  margin-top: 32px;
}

::v-deep .el-select {
  width: 100%;
}

::v-deep .el-drawer__header {
  padding: 17px 0px 17px 20px;
  border: 1px solid #E5E6E9;
  font-weight: 600;
  color: #252525;
  font-size: 16px;
  margin-bottom: 0px;
}

.taskInfo {
  margin: 32px 0 0 74px;

  .InfoTitle {
    font-weight: 600;
    font-size: 14px;
  }

  .martop-16 {
    margin-top: 16px;

    .left {
      color: #808080;
      font-size: 14px;
      display: inline-block;
      width: 133px;
    }

    .right {
      color: #252525;
      font-size: 14px;
    }
  }

  .refresh {
    padding: 7px 8px 6px;
    float: right;
    margin-right: 20px;
  }
}

::v-deep .test-task-dialog .el-dialog__body {
  padding: 20px 60px !important;
}
</style>
